<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "websocket_sever2user".
 *
 * @property int $id
 * @property int $userid
 * @property int $serverid
 * @property string $server_addr
 * @property int $addtime
 */
class WebsocketSever2user extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'websocket_sever2user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['userid', 'serverid', 'server_addr', 'addtime'], 'required'],
            [['userid', 'serverid', 'addtime'], 'integer'],
            [['server_addr'], 'string', 'max' => 30],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'userid' => 'Userid',
            'serverid' => 'Serverid',
            'server_addr' => 'Server Addr',
            'addtime' => 'Addtime',
        ];
    }
    
    public static function checkExist($userid){
        
        if(!preg_match("/^[1-9][0-9]*$/",$userid)){
            echo "错误的用户ID";
            exit;
        }
        $sql = "select count(id) server_num from websocket_sever2user where userid=$userid";
        $command = \Yii::$app->db->createCommand($sql);
        $data = $command->queryOne();
        if($data['server_num'] == 0){
            return false;
        }else{
            return true;
        }
    }
    
    public static function getServerByUserid($userid){
        $model = self::findOne(['userid'=>$userid]);
        if(!empty($model)){
            return $model->server_addr;
        }
        else{
            return "";
        }
    }
}
